package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Override
    public void add(Menu menu) {
        menuDao.add(analysis(menu));
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        //select *from t_menu limit 0,10
        Page<Menu> page = menuDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Menu> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu= menuDao.findById(id);
        return menu;
    }

    @Override
    public void edit(Menu menu) {
        menuDao.edit(analysis(menu));
    }

    @Override
    public void deleteById(Integer id) {
        menuDao.deleteById(id);
    }
    @Override
    public List<Menu> findAll() {
        List<Menu> list = menuDao.findAll();
        return list;
    }

    public Menu analysis(Menu menu){
        String menuPath = menu.getPath();
        //非空判断
        if (menuPath != null) {
            menu.setLevel(1);
            if (menuPath.startsWith("/")) {
                //表明是子菜单
                String[] split = menuPath.substring(1).split("-");
                int level = split.length;
                menu.setLevel(level);
                //父菜单id设置
                String parentPath = split[0];
                String priority = split[1];
                menu.setPriority(Integer.parseInt(priority));
                int parentMenuId = menuDao.findParentIdByParentPath(parentPath);
                menu.setParentMenuId(parentMenuId);
            }else{
                menu.setParentMenuId(null);
            }
        }
        return menu;
    }


}
